package jmu.cze.service.impl;

import jmu.cze.mapper.PersonMapper;
import jmu.cze.service.PersonService;
import jmu.cze.vo.Person;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * 用户管理实现类
 */
@Service
public class PersonServiceImpl implements PersonService {
    private PersonMapper personMapper;

    @Resource(name = "personMapper")
    public void setpersonMapper(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    /**
     * 登录校验
     * @param id, password
     * @return 登陆成功-person，密码错误、用户不存在-null
     */
    public Person signIn(String id, String password, int type) {
        Person person = personMapper.findByID(id);
        if(person != null && person.getPassword().equals(password) && type==person.getType())
            return person;
        return null;
    }

    /**
     * 注册
     * @param person
     * @return 注册成功-true，用户已存在-flase
     */
    public boolean signUp(Person person) throws SQLException {
        return personMapper.add(person) == 1;
    }

    /**
     * 修改用户信息
     * @param person
     * @return 修改成功-true，无此用户-false
     */
    public boolean modify(Person person) {
        return personMapper.update(person) == 1;
    }

    /**
     * 销毁用户
     * @param personID
     * @return 销毁成功-true，无此用户-false
     */
    public boolean destroy(String personID) {
        return personMapper.delete(personID) == 1;
    }

    /**
     * 按id获取用户
     * @param personID
     * @return Person
     */
    public Person findByID(String personID) {
        return personMapper.findByID(personID);
    }

    /**
     * 获取所有的用户
     * @return List<Person>
     */
    public List<Person> findAll(int page, int limit){
        return personMapper.findAll((page-1)*limit,limit);
    }

    /**
     * 按关键字获取用户
     * @param keyword
     * @return List<Person>
     */
    public List<Person> search(String keyword){
        return personMapper.search("%"+keyword+"%");
    }

    /**
     * 获取用户总数
     * @return int
     */
    public int countAll(){
        return personMapper.countAll();
    }
}
